package com.lagou.api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @param null
 * @author oyz
 * @version 1.0
 * @description: 创建节点
 * @date 2022/2/25 9:26
 */
public class CetNodeData implements Watcher {


    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /**
     * 客户端可以通过创建⼀个zk实例来连接zk服务器
     * new Zookeeper(connectString,sesssionTimeOut,Wather)
     * connectString: 连接地址：IP：端⼝
     * sesssionTimeOut：会话超时时间：单位毫秒
     * Wather：监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
     */


    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zooKeeper = new ZooKeeper("192.168.106.128:2181", 5000, new CetNodeData());
        System.out.println(zooKeeper.getState());


        System.out.println("客户端与服务端建立连接成功...");
        Thread.sleep(Integer.MAX_VALUE);


    }
    /**
     path:路径
     watch:是否要启动监听，当⼦节点列表发⽣变化，会触发监听
     zooKeeper.getChildren(path, watch);
     */
    private static void getChildrens() throws KeeperException,
            InterruptedException {
        // 触发监听
        List<String> children = zooKeeper.getChildren("/lg_persistent", true);
        System.out.println(children);
    }



    /**
     * 回调方法：处理来自服务器端的watcher通知
     *
     * @param watchedEvent
     */

    public void process(WatchedEvent watchedEvent) {

        //⼦节点列表发⽣变化时，服务器会发出NodeChildrenChanged通知，但不会把变化情况告 诉给客户端

        // 需要客户端⾃⾏获取，且通知是⼀次性的，需反复注册监听
        if(watchedEvent.getType() ==  Event.EventType.NodeChildrenChanged){
            //再次获取节点数据
            try {
                List<String> children =
                        zooKeeper.getChildren(watchedEvent.getPath(), true);
                System.out.println(children);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //当连接创建了，服务端发送给客户端SyncConnected事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {

            // 获取节点
            try {
                getZookeeperData();
                // 获取节点的子节点列表
                getChildrens();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取节点内容
     */
    private void getZookeeperData() throws UnsupportedEncodingException, KeeperException, InterruptedException {
        /**
         * path : 获取数据的路径
         * watch : 是否开启监听
         * stat : 节点状态信息
         * null: 表示获取最新版本的数据
         * zk.getData(path, watch, stat);
         */
        byte[] data = zooKeeper.getData("/lg_persistent", false, null);
        System.out.println(new String(data,"utf-8"));


    }
}
